<template>
  <canvas ref="pdfCanvas" />
</template>

<script>
export default {
  name: 'Index',
  props: {
    src: {
      type: Object,
      default: null
    },
    page: {
      type: Number,
      default: 1
    }
  },
  watch: {
    src(val) {
      if (val) {
        this.init()
      }
    }
  },
  mounted() {
    if (this.src) {
      this.init()
    }
  },
  methods: {
    init() {
      this.src.getPage(this.page)
        .then(page => {
          let canvas = this.$refs.pdfCanvas
          if (Array.isArray(canvas) && canvas.length) {
            canvas = canvas[0]
          }
          const ctx = canvas.getContext('2d')
          const dpr = window.devicePixelRatio || 1.0
          const bsr = ctx.webkitBackingStorePixelRatio ||
              ctx.mozBackingStorePixelRatio ||
              ctx.msBackingStorePixelRatio ||
              ctx.oBackingStorePixelRatio ||
              ctx.backingStorePixelRatio || 1.0
          const ratio = dpr / bsr
          const viewport = page.getViewport(window.screen.availWidth / page.getViewport(1).width)
          canvas.width = viewport.width * 3 / 10 * ratio - 40
          canvas.height = 180 // viewport.height * ratio
          canvas.style.width = viewport.width * 3 / 10 - 40 + 'px'
          canvas.style.height = 180 + 'px'
          ctx.setTransform(ratio * 3 / 10, 0, 0, 180 / viewport.height * ratio, 0, 0)
          const renderContext = {
            canvasContext: ctx,
            viewport: viewport
          }
          page.render(renderContext)
        })
    }
  }
}
</script>

<style scoped>

</style>
